<style scoped>
.money{display: inline-flex;flex-direction: column;text-align: left;line-height: 1.2;}
.symbol{font-size: 0.8em;}
</style>
<template>
  <div class="money">
    <template v-if="$slots.box">
      <template v-for="(row,i) in list">
        <slot name="box" :index="i" v-bind="row"></slot>
      </template>
    </template>
    <template v-else>
      <p v-for="row in list">
        <slot name="front" v-bind="row"></slot>
        <span class="symbol">{{row.symbol}}</span>
        <span class="value">{{row.valueJoin}}</span>
        <slot name="append" v-bind="row"></slot>
      </p>
    </template>
  </div>
</template>

<script>

import {ref} from "vue";

const moneyList = ref([{symbol:'', rate:1}]);
const defMoney = ref({symbol:'', rate:1});

export function setMoneyList(list){
  moneyList.value = [];
  list.forEach((item)=>{
    item.rate = Number(item.rate);
    if (!item.symbol || !item.rate) return ;
    if (item.rate === 1){
      defMoney.value.symbol = item.symbol;
    }
    moneyList.value.push(item);
  })
  if (moneyList.value <= 0) {
    moneyList.value.push({
      symbol: defMoney.value.symbol,
      rate: defMoney.value.rate
    });
  }
}

setMoneyList([{symbol:'￥', rate:1},{symbol:'$', rate:6}])


export default {
  name: "Money",
  props: {
    value: [String, Number, Array],
    join: {
      type: String,
      default: '~',
    },
    decimal: {
      type: Number,
      default: 2,
    }
  },
  data(){
    return {
      valueList: Array.isArray(this.value) ? this.value : [this.value]
    }
  },
  methods: {

  },
  computed: {
    list() {
      let res = moneyList.value.map(row=>{
        let valueList = this.valueList.map(v=>{
          return ((isNaN(v)?0:v)/row.rate).toFixed(this.decimal);
        })
        let valueJoin = valueList.join(this.join)
        let text = row.symbol+valueJoin;
        return {
          symbol: row.symbol,
          valueList: valueList,
          valueJoin: valueJoin,
          text: text,
        }
      })
      return res;
    }
  },
  watch: {
    value(){
      this.valueList = Array.isArray(this.value) ? this.value : [this.value];
    }
  },
  mounted() {

  }
}
</script>